package com.btcode.reflect;

import com.btcode.common.MyLog;
import com.btcode.exception.MsgException;
import com.btcode.log.ILog;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarClassLoader implements IClassLoader {

    private ILog log;

    private IClassFinder classFinder;

    public JarClassLoader(IClassFinder classFinder) {
        this.classFinder = classFinder;
        log = MyLog.getInstance().getLogger(JarClassLoader.class.getName());
    }

    public List<Class<?>> loadClass(Class<?> myClass, String packetName)
        throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {

        try {
            JarFile file = getFile(myClass);
            Enumeration<JarEntry> entries = file.entries();
            List<Class<?>> classList = new ArrayList<>();

            while (entries.hasMoreElements()) {
                JarEntry entrity = entries.nextElement();

                String className = entrity.getName().replaceAll("/", ".");

                if (className.startsWith(packetName) && !entrity.isDirectory()) {
                    try {
                        String classPath = entrity.getName().replaceAll("/", ".");
                        classPath = classPath.substring(0, classPath.lastIndexOf("."));

                        Class<?> classLoad = myClass.getClassLoader().loadClass(classPath);
                        if (classFinder.isMatch(classLoad)) {
                            classList.add(classLoad);
                        }
                    }
                    catch (Exception e) {
                        log.error("jar类加载出错", e);
                    }

                }
            }
            return classList;

        }
        catch (Exception e) {
            throw new MsgException("加载类出错", e);
        }

    }

    private JarFile getFile(Class<?> myClass) throws IOException {
        String path = myClass.getProtectionDomain().getCodeSource().getLocation().getFile();
        try {
            path = java.net.URLDecoder.decode(path, "UTF-8");
        }
        catch (java.io.UnsupportedEncodingException e) {
            return null;
        }
        log.info("jar路径：" + path);
        JarFile file = new JarFile(new File(path));

        return file;
    }

}
